import React, { useState } from 'react';
import { TextField, Button, Card, CardContent, CardActions, Typography, Container } from '@mui/material';
import AccountCircle from '@mui/icons-material/AccountCircle';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { login as loginApi } from '../api/apiFunctions'; // 使用之前定义的登录方法路径
import store from '../store/store'; // 确保路径正确
import { setAuthState } from '../store/authSlice';

export default function LoginPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false); // 增加加载状态
  const navigate = useNavigate();

  const handleLogin = async () => {
    if (!username || !password) {
      message.warning('请输入用户名和密码');
      return;
    }
    setLoading(true); // 设置加载状态为 true
    try {
      // 调用登录 API 方法
      const data = await loginApi(username, password);
      console.log(data)
      store.dispatch(
        setAuthState({
          isAuthenticated: true,
       
        })
      );
      // localStorage.setItem('roleList', JSON.stringify(data.roleList));
      message.success('登录成功');
      navigate('/');
    } catch (error) {
      // 显示错误提示
      message.error(`登录--失败: ${error.message || '请稍后再试'}`);
    } finally {
      setLoading(false); // 重置加载状态
    }
  };

  return (
    <Container
      maxWidth="sm"
      sx={{
        display: 'flex',
        height: '100vh',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Card sx={{ width: '100%', p: 2 }}>
        <Typography variant="h5" sx={{ textAlign: 'center', mb: 2 }}>
          登录
        </Typography>
        <CardContent>
          <TextField
            fullWidth
            label="用户"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            margin="normal"
            InputProps={{
              startAdornment: <AccountCircle />,
            }}
          />
          <TextField
            fullWidth
            label="密码"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            margin="normal"
            InputProps={{
              startAdornment: <LockOutlinedIcon />,
            }}
          />
        </CardContent>
        <CardActions
          sx={{
            flexDirection: 'column',
            alignItems: 'center',
            '& > *': { mb: 1 },
          }}
        >
          <Button
            variant="contained"
            sx={{ backgroundColor: '#088f11' }}
            onClick={handleLogin}
            disabled={loading} // 登录时禁用按钮
          >
            {loading ? '登录中...' : '登录'}
          </Button>
        </CardActions>
      </Card>
    </Container>
  );
}
